<?php


namespace App\Http\Controllers;


use App\Models\User;
use App\Server\AliOSS;
use App\Server\Token;
use Illuminate\Http\Request;
use \App\Server\EasyWeChat\MiniProgram;

class UserController extends Controller
{
    /**
     * 登录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \Throwable
     */
    public function login(Request $request)
    {
        if ($request->local_uid) {
            $user = User::where('id', $request->local_uid)->first();
        } else {
            $res = MiniProgram::userSession($request->js_code);
            $user = User::where('openid', $res['openid'])->first();
        }

        throw_err($user && $user->status == 0, '登录异常');

        if (!$user) {
            $user = new User();
            $user->openid = $res['openid'];
            $user->name = $request->name;
            $user->avatar = $request->avatar;
            $user->save();
        }

        $token = Token::create($user->id, $user->id . time());

        $data = [
            'token' => $token,
            'user' => [
                'name' => $user->name,
                'avatar' => $user->avatar,
                'is_anchor' => $user->is_anchor,
            ]
        ];
        return $this->success($data);
    }

    /**
     * 获取用户信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function info(Request $request)
    {
        $user = User::where('id', $request->uid)->first();
        $user->avatar = img_url($user->avatar);
        return $this->success($user);
    }

    /**
     * 编辑用户信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \OSS\Core\OssException
     * @throws \Throwable
     */
    public function setInfo(Request $request)
    {
        throw_err(strlen($request->nickname) > 20, '昵称长度超过限制');
        $data = [];
        if ($request->nickname) {
            $data['name'] = $request->nickname;
        }
        if ($request->avatar) {
            $data['avatar'] = (new AliOSS())->putBase64Object($request->avatar);
        }
        if ($data) {
            User::where('id', $request->uid)->update($data);
        }
        return $this->success();
    }

}